File Handling
In Java, file handling is done using classes from the java.io package. The three basic operations are:
The file class is used to create a new file.
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File file = new File("student.txt");
//create a file object
if (file.createNewFile()) {
//Creates the file if it does not already exist.
//Returns ture if created successfully else false
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
The FileWriter class is used to write text into a file.
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("student.txt");
//Opens the file for writing.
writer.write("Name: Sheetal\n");
writer.write("Age: 21\n");
writer.write("Faculty: Science\n");
writer.close();
System.out.println("Data written successfully.");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
To add new data without deleting the existing content.
FileWriter writer = new FileWriter("student.txt", true);
//The second parameter true enables append mode.
writer.write("Address: Kathmandu\n");
writer.close();
The Scanner class can be used to read data from a file.
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("student.txt");
Scanner sc = new Scanner(file);
//Opens the file for reading
while(sc.hasNextLine()) {
//Checks if another line exists
String line = sc.nextLine();
//Reads one line at a time
System.out.println(line);
}
sc.close();
//Closes the file after reading
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}